package com.jingding.procurement.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.jingding.procurement.enumeration.EntityEnum;
import com.jingding.procurement.mapper.SellOutMapper;
import com.jingding.procurement.pojo.entity.Entity;
import com.jingding.procurement.pojo.entity.SellOutEntity;
import com.jingding.procurement.pojo.vo.SellOutVO;
import com.jingding.procurement.service.SellOutService;
import com.jingding.procurement.util.IO;
import com.jingding.procurement.util.Requesting;
import com.jingding.procurement.web.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

@Service
@Slf4j
public class SellOutServiceImpl implements SellOutService {

    @Autowired
    private SellOutMapper mapper;

    @Value("${SOE_url}")
    private String SOE_url;

    @Override
    public JsonResult pushSellOut(Entity entity, String secondTime) throws IOException, ClassNotFoundException {
        List<SellOutVO> sellOutVOS = mapper.selpushSellOutVO(entity.getStartTime(), entity.getEndTime());
        if (sellOutVOS.size()<1){
            log.debug("暂无[销售出库],下次任务开始时间不做变更,时间为:{} ,暂不推送数据  " , secondTime);;
            return JsonResult.ok("暂无[销售出库],下次任务开始时间不做变更 时间为:  " + secondTime);
        }
        String jsonObject = Requesting.httpPost(SOE_url,
                JSON.toJSONString(sellOutVOS, SerializerFeature.WriteNullStringAsEmpty));
        SellOutEntity sellOutEntity = IO.sellOutRead();
        if (JSON.parseObject(jsonObject).getObject("code", (Type) String.class).equals("200")) {
            sellOutEntity.setStartTime(secondTime);
            IO.sellOutWrite(sellOutEntity);
            log.debug("[销售出库]起始时间修改完成:{}", secondTime);
            //return JsonResult.ok("[销售出库]推送成功,下次任务开始时间为:  " + secondTime);
            return JsonResult.ok(sellOutVOS);
        }
        log.debug("[销售出库]推送失败: {}",sellOutVOS);
        return JsonResult.fail(400, "[销售出库]推送失败,下次任务开始时间为:  " + sellOutEntity.getStartTime()+"失败原因: "+jsonObject+"\\n" +
                "推送内容:"+JSON.toJSONString(sellOutVOS, SerializerFeature.WriteNullStringAsEmpty));

    }

}
